package fr.ssd.sdl;

import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

import fr.ssd.sdl.config.Configurator;
import fr.ssd.sdl.loader.Loader;
import fr.ssd.sdl.loader.LoaderException;
import fr.ssd.sdl.loader.SimpleSqlLoader;
import fr.ssd.sdl.parser.ParserImpl;
import fr.ssd.sdl.resolver.KeyResolver;
import fr.ssd.sdl.resolver.KeyResolverImpl;
import fr.ssd.sdl.resolver.ResolverException;
import fr.ssd.sdl.store.Store;
import fr.ssd.sdl.store.StoreException;
import fr.ssd.sdl.store.file.FileBackend;
import fr.ssd.sdl.store.jdbc.JdbcBackend;
import fr.ssd.sdl.store.mux.Multiplexer;
import fr.ssd.sdl.store.mux.SequentialMultiplexer;
import fr.ssd.sdl.store.terminal.TerminalBackend;

public class SqlDataLoader implements Runnable {

	protected Map<String, Object> hints = new HashMap<String, Object>();
	protected Loader l = new SimpleSqlLoader();
	protected KeyResolver r = new KeyResolverImpl();
	protected Store b = new SequentialMultiplexer();
	
	public SqlDataLoader() {
		hints.put("sourceFileName", Configurator.sourceFileName);
		hints.put("storeFileName", Configurator.storeFileName);
		if(Configurator.fileBackend){
			((Multiplexer)b).addStore(new FileBackend());
		}
		if(Configurator.jdbcBackend){
			((Multiplexer)b).addStore(new JdbcBackend());
		}
		if(Configurator.terminalBackend){
			((Multiplexer)b).addStore(new TerminalBackend());
		}
		
		((KeyResolverImpl)r).setParser(new ParserImpl());
	}

	@Override
	public void run() {
		String statement;
		try {
			l.init(hints);
			b.init(hints);
			statement = l.loadSqlStatement();
			while (statement != null) {
				statement = r.resolve(statement);
				b.store(statement);
				statement = l.loadSqlStatement();
			}
			b.terminate();
		} catch (StoreException e) {
			e.printStackTrace();
		} catch (LoaderException e) {
			e.printStackTrace();
		} catch (ResolverException e) {
			e.printStackTrace();
		}

	}

	/**
	 * @param args
	 * @throws FileNotFoundException 
	 * @throws LoaderException 
	 */
	public static void main(String[] args) throws LoaderException {
		new SqlDataLoader().run();
	}

}
